#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <pthread.h>

char 	*node[2] ;
int 	 fd[2];

void *thread_recv(void *arg)
{
    char rbuf[256];
    int i;

    while(1) {
        read(fd[1], rbuf, 1);
        printf("		r%d\n", rbuf[0]);
    }

    return NULL;
}

int main(int argc, char *argv[])
{
    pthread_t pid;
    int i;

    {/* usage */
        if (argc != 3) {
            printf("%s sendport recvport\n", argv[0]);
            exit(-1);
        }
        node[0] = argv[1];
        node[1] = argv[2];
    }//

    {/* open serials */
        for (i = 0; i < 2; i++) {
            fd[i] = open(node[i], O_RDWR | O_NOCTTY | O_NDELAY);
            if (fd[i] < 0) {
                printf("failed ot open %s\n", node[i]);
                perror("\n\t");
                exit(-1);
            }
            if (fcntl(fd[i], F_SETFL, 0) < 0)
                perror("fcntl");
        }

    }

    {/* configure serials */
        for (i = 0; i < 2; i++) {
            struct termios termios;

                tcgetattr(fd[i], &termios);
            cfsetospeed(&termios, B9600);
            cfsetispeed(&termios, B9600);
            termios.c_iflag &= ~(INLCR | IGNCR | ICRNL | ISTRIP);
            termios.c_oflag &= ~(OPOST | ONLCR | OCRNL);
            termios.c_lflag &= ~(ISIG  | ECHO  | ICANON | NOFLSH);
            termios.c_cflag &= ~CSIZE;
            termios.c_cflag |= CS8 | CREAD;
            termios.c_cflag &= ~PARENB;
            termios.c_cflag &= ~CSTOPB;
            tcsetattr(fd[i], TCSANOW, &termios);
        }
    }

    {/* start receive thread */
        int ret;

        ret = pthread_create(&pid, NULL, thread_recv, NULL);
        if (ret < 0) {
            perror("pthread");
            exit(-1);
        }
    }

    {/* poll write */
        char wbuf[256];

        for (i = 0; i < 256; i++) {
            wbuf[i] = i;
        }

        while (1) {
            if (write(fd[0], &wbuf, 256) != 256) {
                perror("write");
                break;
            }
            printf("send a msg\n");
            usleep(1000000);
        }
    }

    {/* close serials */
        for (i = 0; i < 2; i++) {
            close(fd[i]);
        }
    }

    return 0;
}

